package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.UUIDUtils;
import cn.stylefeng.guns.sys.modular.system.db4.mapper.TeamMapper;
import cn.stylefeng.guns.sys.modular.system.entity.*;
import cn.stylefeng.guns.sys.modular.system.mapper.*;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyCuibanParam;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyGufenzhuanrangParam;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyGufenzhuanrangShepiParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyCuibanResult;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyGufenzhuanrangResult;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyGufenzhuanrangShepiResult;
import cn.stylefeng.guns.sys.modular.system.model.result.GufenzhuanrangResult;
import cn.stylefeng.guns.sys.modular.system.service.*;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import oshi.jna.platform.mac.SystemB;

import javax.annotation.Resource;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yxc
 * @since 2021-05-31
 */
@Service
public class BtyGufenzhuanrangServiceImpl extends ServiceImpl<BtyGufenzhuanrangMapper, BtyGufenzhuanrang> implements BtyGufenzhuanrangService {

    private static Logger logger = LoggerFactory.getLogger(BtyGufenzhuanrangServiceImpl.class);

    @Resource
    private UserMapper userMapper;
    @Resource
    private BtyGufenzhuanrangShepiMapper btyGufenzhuanrangShepiMapper;
    @Resource
    private TeamMapper teamMapper;
    @Resource
    private WeChatSendTempMsgService weChatSendTempMsgService;
    @Resource
    private BtyWxMapper btyWxMapper;
    @Resource
    private BtyBrandMapper btyBrandMapper;
    @Resource
    private UserService userService;
    @Resource
    private BtyCuibanMapper btyCuibanMapper;
    @Resource
    private BtyCuibanService btyCuibanService;
    @Resource
    private PushMsgService pushMsgService;

    @Override
    public void add(BtyGufenzhuanrangParam param, String account) {

        if (ToolUtil.isNotEmpty(account)) {

            //登陆者是 转让方 或 受让方 可以提交信息
            if (account.equals(param.getZrTel()) || account.equals(param.getSrTel())) {

                //获取用户id
                Long userId = userMapper.getUserId(account);
                Date date = new Date();
                param.setRiqi(date);//申请日期
                param.setCreateUser(userId);//创建人
                BtyGufenzhuanrang entity = getEntity(param);
                int i = this.baseMapper.insertGf(entity);//股份转让表新增数据

                BtyGufenzhuanrangShepi btyGufenzhuanrangShepi = new BtyGufenzhuanrangShepi();
                btyGufenzhuanrangShepi.setBtyGufenzhuanrangId(entity.getBtyGufenzhuanrangId());
                btyGufenzhuanrangShepi.setJiedian(1);//1 受让方审核
                btyGufenzhuanrangShepi.setShStatus("1");//1 待审批
                btyGufenzhuanrangShepi.setCreateUser(userId);//创建人
                btyGufenzhuanrangShepi.setUpdateTime(new Date());


//            this.save(entity);//股份转让表新增数据

                int j = btyGufenzhuanrangShepiMapper.insert(btyGufenzhuanrangShepi);//审批表新增数据

                if (i > 0 && j > 0) {

                    String now = DateUtil.getNow();//当前时间
                    //获取当前店名
                    String dm = btyBrandMapper.getDm(param.getShopId());
                    String data = param.getZrName() + "发起了关于" + dm + "的股份转让，需要您审批，请登录web端或小妖app及时处理！";
                    JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "股份转让审批", "股份转让审批", now, data);

                    //获取受让方openid
                    User user = btyWxMapper.getOpenId(param.getSrTel());
                    String[] openid = null;
                    if (ToolUtil.isNotEmpty(user)) {
                        openid = new String[]{user.getOpenid()};
                    }

                    weChatSendTempMsgService.sendmsg(openid, BusConst.MSURL, tempObj);
                    logger.info("======已推送受让方审核消息======");
                }
            }
        }
    }

    @Override
    public void delete(BtyGufenzhuanrangParam param) {
        this.removeById(getKey(param));
    }

    @Override
    public void update(BtyGufenzhuanrangParam param, String account) {

        if (ToolUtil.isNotEmpty(account)) {

            Date date = new Date();
            //获取用户id
            Long userId = userMapper.getUserId(account);

            //查询转让方电话
            Map map = this.baseMapper.getZrTel(param.getBtyGufenzhuanrangId());

            //转让方 或 受让方 可修改
            if (ToolUtil.isNotEmpty(map) && (map.get("zrTel").equals(account) || map.get("srTel").equals(account))) {
                if (map.get("jiedian").equals(1) || (!map.get("jiedian").equals(1) && map.get("shStatus").equals("2"))) {
                    BtyGufenzhuanrang oldEntity = getOldEntity(param);
                    BtyGufenzhuanrang newEntity = getEntity(param);
                    ToolUtil.copyProperties(newEntity, oldEntity);
                    this.updateById(newEntity);

//                    if (!map.get("jiedian").equals(1) && map.get("shStatus").equals("2")){

                    //将驳回数据改为未审核
                    BtyGufenzhuanrangShepi sp = new BtyGufenzhuanrangShepi();
                    sp.setBtyGufenzhuanrangShepiId(Long.parseLong(map.get("btyGufenzhuanrangShepiId").toString()));
                    sp.setShStatus("1");//待审核
                    sp.setUpdateUser(userId);
                    sp.setUpdateTime(date);

                    int i = btyGufenzhuanrangShepiMapper.updateById(sp);

                    if (i > 0) {

                        String now = DateUtil.getNow();//当前时间
                        //获取当前店名
                        String dm = btyBrandMapper.getDm(param.getShopId());
                        String data = param.getZrName() + "发起了关于" + dm + "的股份转让，需要您审批，请登录web端或小妖app及时处理！";
                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "股份转让审批", "股份转让审批", now, data);

                        String[] openid = null;

                        if (map.get("jiedian").equals(1)) {
                            //获取受让方openid
                            User user = btyWxMapper.getOpenId(param.getSrTel());
                            if (ToolUtil.isNotEmpty(user)) {
                                openid = new String[]{user.getOpenid()};
                            }
                        } else if (map.get("jiedian").equals(2)) {
                            //查询该店督导
                            String ddTel = teamMapper.getDd(param.getShopId());
                            User ddUser = btyWxMapper.getOpenId(ddTel);
                            if (ToolUtil.isNotEmpty(ddUser)) {
                                openid = new String[]{ddUser.getOpenid()};
                            }
                        } else if (map.get("jiedian").equals(3)) {

                            //查询该店营运经理
                            String yyTel = teamMapper.getYy(param.getShopId());
                            User yyUser = btyWxMapper.getOpenId(yyTel);
                            if (ToolUtil.isNotEmpty(yyUser)) {
                                openid = new String[]{yyUser.getOpenid()};
                            }
                        } else if (map.get("jiedian").equals(4)) {

                            //总部股份审核
                            Long role = 1399903894637486082L;//总部股份审核
                            List<String> openidlist = userService.listOpenidsByRole(role);
                            if (ToolUtil.isNotEmpty(openidlist)) {
                                openid = openidlist.toArray(new String[openidlist.size()]);
                            }
                        } else if (map.get("jiedian").equals(5)) {

                            //财务股份审核
                            Long cwRole = 1399903976661295105L;//财务股份审核
                            List<String> cwlist = userService.listOpenidsByRole(cwRole);
                            if (ToolUtil.isNotEmpty(cwlist)) {
                                openid = cwlist.toArray(new String[cwlist.size()]);
                            }
                        }

                        weChatSendTempMsgService.sendmsg(openid, BusConst.MSURL, tempObj);
                        logger.info("======已推送审核消息======");
                    }
//                    }
                }
            }
        }

    }

    @Override
    public BtyGufenzhuanrangResult findBySpec(BtyGufenzhuanrangParam param) {
        return null;
    }

    @Override
    public List<BtyGufenzhuanrangResult> findListBySpec(BtyGufenzhuanrangParam param) {
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(BtyGufenzhuanrangParam param) {
        String account = LoginContextHolder.getContext().getUser().getAccount();
        //查询督导所有的店
        List<String> list = null;
        List<String> ddList = null;
        param.setUserTel(account);
        param.setCreateUser(LoginContextHolder.getContext().getUser().getId());
        /* 1、受让方审核；2、督导审核；3、城市经理审核；4、总部审核；5、财务审核、*/
        //获取当前用户角色列表
        List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();

        if (roleNames.contains("总部股份审核")) {
            param.setJiedian("4");

        }else if (roleNames.contains("营运经理")) {
            //查询营运经理所有的店
            list = teamMapper.getYyCode(account);
            //查询为督导所有的店
            ddList = teamMapper.getDdCode(account);

            if (ddList.size() > 0){
                param.setIsdd("1");
            }

            if (list.size() > 0){
                param.setJiedian("3");
            }else {
                param.setJiedian("1");
            }

        }else if (roleNames.contains("督导")) {
            list = teamMapper.getDdCode(account);

            if (list.size() > 0) {
                param.setJiedian("2");
            }else {
                param.setJiedian("1");
            }

        }else if (roleNames.contains("财务股份审核")) {
            param.setJiedian("5");

        } else {
            param.setJiedian("1");
        }
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param, list, ddList);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 获取门店列表
     */
    @Override
    public List<Map<String, Object>> getDm() {
        return this.baseMapper.getDm();
    }

    /**
     * 获取转让人列表
     */
    @Override
    public List<BtyGufenzhuanrangParam> getZr() {
        return this.baseMapper.getZr();
    }

    /**
     * 获取受让人列表
     */
    @Override
    public List<BtyGufenzhuanrangParam> getSr() {
        return this.baseMapper.getSr();
    }

    /**
     * 审核
     */
    @Override
    @Transactional
    public int passOrRebut(Long id, Long fatherId, Integer status, String shopCode, String reason, Integer jiedian, String zrTel) {
        /* 1、受让方审核；2、督导审核；3、城市经理审核；4、总部审核；5、财务审核、*/
        String account = LoginContextHolder.getContext().getUser().getAccount();
        String shName = LoginContextHolder.getContext().getUser().getName();
        String[] openid = null;
        int sta = 0;
        //查询该店督导
        String ddTel = teamMapper.getDd(shopCode);
        //查询该店营运经理
        String yyTel = teamMapper.getYy(shopCode);

        //总部股份审核
        Long role = 1399903894637486082L;//总部股份审核
        List<String> openidlist = userService.listOpenidsByRole(role);

        /* 1、受让方审核；2、督导审核；3、城市经理审核；4、总部审核；5、财务审核、*/
        if (jiedian == 1) {
            //推送督导
            User ddUser = btyWxMapper.getOpenId(ddTel);
            if (ToolUtil.isNotEmpty(ddUser)) {
                openid = new String[]{ddUser.getOpenid()};
            }
        } else if (jiedian == 2){//2、督导审核；
            shName = "督导" + shName;

            //若当前登陆者既是该店营运经理又是督导
            if (account.equals(ddTel) && account.equals(yyTel)){
                sta = 1;
                //推送总部
                if (ToolUtil.isNotEmpty(openidlist)) {
                    logger.info("=========总部股份审核:" + openidlist + "========");
                    openid = openidlist.toArray(new String[openidlist.size()]);
                }
            }else {
                //推送营运经理
                User yyUser = btyWxMapper.getOpenId(yyTel);
                if (ToolUtil.isNotEmpty(yyUser)) {
                    openid = new String[]{yyUser.getOpenid()};
                }
            }

        }else if (jiedian == 3){//3、城市经理审核；
            shName = "营运经理" + shName;

            //推送总部
            if (ToolUtil.isNotEmpty(openidlist)) {
                logger.info("=========总部股份审核:" + openidlist + "========");
                openid = openidlist.toArray(new String[openidlist.size()]);
            }
        }else if (jiedian == 4){//4、总部审核；
            shName = "营运总监" + shName;

            //财务股份审核
            Long cwRole = 1399903976661295105L;//财务股份审核
            List<String> cwlist = userService.listOpenidsByRole(cwRole);

            //推送财务
            if (ToolUtil.isNotEmpty(cwlist)) {
                logger.info("=========财务股份审核:" + cwlist + "========");
                openid = cwlist.toArray(new String[cwlist.size()]);
            }
        }else if (jiedian == 5){
            shName = "财务" + shName;
        }
        Date date = new Date();
        Long name = LoginContextHolder.getContext().getUserId();
        BtyGufenzhuanrangShepi sp = new BtyGufenzhuanrangShepi();
        sp.setBtyGufenzhuanrangShepiId(id);
        sp.setShStatus(status + "");
        sp.setShenpiYijina(reason);
        sp.setUpdateUser(name);
        sp.setUpdateTime(date);
        sp.setShenpiShijian(date);
        sp.setShenpiRen(name.toString());
        if (status == 3 && jiedian != 5) {

            //查询是否有此节点
            int con = btyGufenzhuanrangShepiMapper.getCon(fatherId, jiedian + 1);
            if (con <= 0){
                if (sta == 0){
                    BtyGufenzhuanrangShepi sp1 = new BtyGufenzhuanrangShepi();
                    sp1.setBtyGufenzhuanrangId(fatherId);
                    sp1.setShStatus("1");
                    sp1.setJiedian(jiedian + 1);
                    sp1.setCreateTime(new Date());
                    sp1.setCreateUser(name);
                    btyGufenzhuanrangShepiMapper.insert(sp1);

                } else if (sta == 1 && jiedian == 2){//当前登陆者既是该店营运经理又是督导,审批一遍，新增两个节点
                    BtyGufenzhuanrangShepi sp1 = new BtyGufenzhuanrangShepi();
                    sp1.setBtyGufenzhuanrangId(fatherId);
                    sp1.setShStatus("3");
                    sp1.setJiedian(jiedian + 1);
                    sp1.setCreateTime(new Date());
                    sp1.setCreateUser(name);
                    sp1.setUpdateTime(new Date());
                    sp1.setShenpiRen(name.toString());
                    sp1.setShenpiShijian(new Date());
                    sp1.setUpdateUser(name);
                    btyGufenzhuanrangShepiMapper.insert(sp1);//新增城市经理审核通过

                    BtyGufenzhuanrangShepi sp2 = new BtyGufenzhuanrangShepi();
                    sp2.setBtyGufenzhuanrangId(fatherId);
                    sp2.setCreateTime(new Date());
                    sp2.setCreateUser(name);
                    sp2.setUpdateTime(new Date());
                    sp2.setShStatus("1");
                    sp2.setJiedian(jiedian + 2);
                    btyGufenzhuanrangShepiMapper.insert(sp2);//新增总部待审核
                }
            }

        }
        int i = this.baseMapper.updatePassOrBut(sp);
        String now = DateUtil.getNow();//当前时间
        if (i > 0 && status == 3) {
            //获取当前店名
            String dm = btyBrandMapper.getDm(shopCode);
            String zrName = this.baseMapper.getZrName(fatherId);
            String data = zrName + "发起了关于" + dm + "的股份转让，需要您审批，请登录web端或小妖app及时处理！";
            JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "股份转让审批", "股份转让审批", now, data);
            weChatSendTempMsgService.sendmsg(openid, BusConst.MSURL, tempObj);
            logger.info("======已推送审核消息======");

            //驳回推送受让方消息
        }else if (i > 0 && status == 2){
            //获取此任务的受让方电话,店名
            Map srMap = baseMapper.getSrById(fatherId);
            Map<String, String> map = new HashMap<>();
            map.put("srTel", srMap.get("srTel").toString());
            map.put("name", shName);
            map.put("dm", srMap.get("dm").toString());
            map.put("reason", reason);
            pushMsgService.gufeneiToIM(map, now);
        }
        return i;
    }

    private Serializable getKey(BtyGufenzhuanrangParam param) {
        return param.getBtyGufenzhuanrangId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BtyGufenzhuanrang getOldEntity(BtyGufenzhuanrangParam param) {
        return this.getById(getKey(param));
    }

    private BtyGufenzhuanrang getEntity(BtyGufenzhuanrangParam param) {
        BtyGufenzhuanrang entity = new BtyGufenzhuanrang();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    /**
     * 股份转让列表
     *
     * @param param
     * @return
     */
    @Override
    public Object gufenList(BtyGufenzhuanrangParam param, String account) {
        if (ToolUtil.isNotEmpty(account)) {
            Page pageContext = getPageContext();
            IPage page = null;

            //领导驳回列表
            if (ToolUtil.isNotEmpty(param.getShStatus()) && param.getShStatus()== 4){
                //获取是受让方时被领导驳回的数据
                page = this.baseMapper.guBhList(pageContext, param, account);

            }else {
                List<String> list = null;
                List<String> ddList = null;
                //获取用户角色名称
                List<String> roleNames = roleList(account);
                param.setUserTel(account);

                if (roleNames.contains("总部股份审核")) {

                    param.setJiedian("4");

                }else if (roleNames.contains("营运经理")) {

                    //查询营运经理所有的店
                    list = teamMapper.getYyCode(account);
                    //查询为督导所有的店
                    ddList = teamMapper.getDdCode(account);

                    if (ddList.size() > 0){
//                    list.addAll(ddList);
//                    param.setJiedian("2");
                        param.setIsdd("1");
                    }
                    if (list.size() > 0) {
                        param.setJiedian("3");
                    }else if (ddList.size() > 0){
                        param.setJiedian("2");
                    }else {
                        param.setJiedian("1");
                    }

                } else if (roleNames.contains("督导")) {
                    //查询督导所有的店
                    list = teamMapper.getDdCode(account);

                    if (list.size() > 0) {
                        param.setJiedian("2");
                    }else {
                        param.setJiedian("1");
                    }

                } else if (roleNames.contains("财务股份审核")) {

                    param.setJiedian("5");

                } else {

                    param.setJiedian("1");//受让方列表

                }

                page = this.baseMapper.gufenDdList(pageContext, param, list,ddList);
                List<BtyGufenzhuanrangResult> records = page.getRecords();
                if (ToolUtil.isNotEmpty(records)){

                    //先排序，再根据btyGufenzhuanrangId过滤去重
                    records = records.stream().sorted((h1, h2) -> Integer.valueOf(h2.getJiedian()) - Integer.valueOf(h1.getJiedian())).
                            filter(distinctById(BtyGufenzhuanrangResult::getBtyGufenzhuanrangId)).collect(Collectors.toList());

                    page.setRecords(records);
                    page.setTotal(records.size());
                }
            }

            return LayuiPageFactory.createPageInfo(page);
        }else {
            LayuiPageInfo result = new LayuiPageInfo();
            result.setCount(0);
            result.setData(null);
            return result;
        }
    }

    public static <T> Predicate<T> distinctById(Function<? super T, ?> keyExtractor) {
        Set<Object> seen = ConcurrentHashMap.newKeySet();
        return t -> seen.add(keyExtractor.apply(t));
    }

    /**
     * 获取用户角色名称
     *
     * @param account
     * @return
     */
    public List<String> roleList(String account) {

        User user = null;
        //获取用户角色
        user = userMapper.getByAccount(account);
        if (ToolUtil.isEmpty(user)){
            user = userMapper.getAccount(account);
        }
        List<String> roleNames = new ArrayList<>();
        if (ToolUtil.isNotEmpty(user)) {
            String userName = user.getName();//用户名字
            String roleId = user.getRoleId();//用户角色id
            String phone = user.getPhone();//用户电话
            List rolds = Arrays.asList(roleId.split(","));
            //获取用户角色名称
            roleNames = userMapper.getRole(rolds);
        }

        return roleNames;

    }

    /**
     * 股份转让详情
     *
     * @return
     */
    @Override
    public List<Map> gufenById(Long id, String shopId) {
        Map map = teamMapper.getDdName(shopId);
        List<Map> list = this.baseMapper.gufenById(id);
        List<Map> list1 = new ArrayList<>();
        for (Map map1 : list) {

            if(ToolUtil.isNotEmpty(map)){
                if (ToolUtil.isNotEmpty(map.get("dd"))){
                    map1.put("dd", map.get("dd"));
                }
                if (ToolUtil.isNotEmpty(map.get("yy"))){
                    map1.put("yy", map.get("yy"));
                }
            }
            list1.add(map1);

        }
        return list1;
    }

    /**
     * 审批接口
     *
     * @param account
     */
    @Override
    @Transactional
    public void approved(BtyGufenzhuanrangShepiParam param, String account) {

        if (ToolUtil.isNotEmpty(account)) {
            //获取用户id
            Long userId = userMapper.getUserId(account);
            //获取用户姓名
            String name = userMapper.getNameByAccount(account);

            int sta = 0;
            int jiedian = param.getJiedian();
            String[] openid = null;

            //查询该店督导
            String ddTel = teamMapper.getDd(param.getShopId());
            //查询该店营运经理
            String yyTel = teamMapper.getYy(param.getShopId());
            //总部股份审核
            Long role = 1399903894637486082L;//总部股份审核
            List<String> openidlist = userService.listOpenidsByRole(role);

            /* 1、受让方审核；2、督导审核；3、城市经理审核；4、总部审核；5、财务审核、*/
            if (jiedian == 1) {
                //推送督导
                User ddUser = btyWxMapper.getOpenId(ddTel);
                if (ToolUtil.isNotEmpty(ddUser)) {
                    openid = new String[]{ddUser.getOpenid()};
                }
            } else if (jiedian == 2){//2、督导审核；
                name = "督导" + name;

                //若当前登陆者既是该店营运经理又是督导
                if (account.equals(ddTel) && account.equals(yyTel)){
                    sta = 1;
                    //推送总部
                    if (ToolUtil.isNotEmpty(openidlist)) {
                        logger.info("=========总部股份审核:" + openidlist + "========");
                        openid = openidlist.toArray(new String[openidlist.size()]);
                    }
                }else {
                    //推送营运经理
                    User yyUser = btyWxMapper.getOpenId(yyTel);
                    if (ToolUtil.isNotEmpty(yyUser)) {
                        openid = new String[]{yyUser.getOpenid()};
                    }
                }

            }else if (jiedian == 3){//3、城市经理审核；
                name = "营运经理" + name;

                //推送总部
                if (ToolUtil.isNotEmpty(openidlist)) {
                    logger.info("=========总部股份审核:" + openidlist + "========");
                    openid = openidlist.toArray(new String[openidlist.size()]);
                }
            }else if (jiedian == 4){//4、总部审核；
                name = "营运总监" + name;

                //财务股份审核
                Long cwRole = 1399903976661295105L;//财务股份审核
                List<String> cwlist = userService.listOpenidsByRole(cwRole);

                //推送财务
                if (ToolUtil.isNotEmpty(cwlist)) {
                    logger.info("=========财务股份审核:" + cwlist + "========");
                    openid = cwlist.toArray(new String[cwlist.size()]);
                }
            }else if (jiedian == 5){
                name = "财务" + name;
            }
            Date date = new Date();

            BtyGufenzhuanrangShepi sp = new BtyGufenzhuanrangShepi();
            sp.setBtyGufenzhuanrangShepiId(param.getBtyGufenzhuanrangShepiId());
            sp.setShStatus(param.getShStatus());
            sp.setShenpiYijina(param.getShenpiYijina());
            sp.setUpdateUser(userId);
            sp.setUpdateTime(date);
            sp.setShenpiShijian(date);
            sp.setShenpiRen(userId.toString());

            if (param.getShStatus().equals("3") && jiedian != 5) {

                //查询是否有此节点
                int con = btyGufenzhuanrangShepiMapper.getCon(param.getBtyGufenzhuanrangId(), jiedian + 1);
                if (con <= 0){
                    if (sta == 0){
                        BtyGufenzhuanrangShepi sp1 = new BtyGufenzhuanrangShepi();
                        sp1.setBtyGufenzhuanrangId(param.getBtyGufenzhuanrangId());
                        sp1.setShStatus("1");
                        sp1.setJiedian(jiedian + 1);
                        sp1.setCreateTime(new Date());
                        sp1.setCreateUser(userId);
                        btyGufenzhuanrangShepiMapper.insert(sp1);

                    } else if (sta == 1 && jiedian == 2){//当前登陆者既是该店营运经理又是督导,审批一遍，新增两个节点
                        BtyGufenzhuanrangShepi sp1 = new BtyGufenzhuanrangShepi();
                        sp1.setBtyGufenzhuanrangId(param.getBtyGufenzhuanrangId());
                        sp1.setShStatus("3");
                        sp1.setJiedian(jiedian + 1);
                        sp1.setCreateTime(new Date());
                        sp1.setCreateUser(userId);
                        sp1.setUpdateTime(new Date());
                        sp1.setShenpiRen(userId.toString());
                        sp1.setShenpiShijian(new Date());
                        sp1.setUpdateUser(userId);
                        btyGufenzhuanrangShepiMapper.insert(sp1);//新增城市经理审核通过

                        BtyGufenzhuanrangShepi sp2 = new BtyGufenzhuanrangShepi();
                        sp2.setBtyGufenzhuanrangId(param.getBtyGufenzhuanrangId());
                        sp2.setCreateTime(new Date());
                        sp2.setCreateUser(userId);
                        sp2.setUpdateTime(new Date());
                        sp2.setShStatus("1");
                        sp2.setJiedian(jiedian + 2);
                        btyGufenzhuanrangShepiMapper.insert(sp2);//新增总部待审核
                    }
                }

            }
            int i = btyGufenzhuanrangShepiMapper.updateById(sp);

            String now = DateUtil.getNow();//当前时间
            if (i > 0 && "3".equals(param.getShStatus())) {

                //获取当前店名
                String dm = btyBrandMapper.getDm(param.getShopId());
                String zrName = this.baseMapper.getZrName(param.getBtyGufenzhuanrangId());
                String data = zrName + "发起了关于" + dm + "的股份转让，需要您审批，请登录web端或小妖app及时处理！";
                JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "股份转让审批", "股份转让审批", now, data);

                weChatSendTempMsgService.sendmsg(openid, BusConst.MSURL, tempObj);
                logger.info("======已推送审核消息======");

                //驳回推送受让方消息
            }else if (i > 0 && "2".equals(param.getShStatus())){
                //获取此任务的受让方电话,店名
                Map srMap = baseMapper.getSrById(param.getBtyGufenzhuanrangId());
                Map<String, String> map = new HashMap<>();
                map.put("srTel", srMap.get("srTel").toString());
                map.put("name", name);
                map.put("dm", srMap.get("dm").toString());
                map.put("reason", param.getShenpiYijina());
                pushMsgService.gufeneiToIM(map, now);
            }
        }
    }

    /**
     * 股份转让列表（发起方）
     *
     * @param param
     * @param account
     * @return
     */
    @Override
    public Object fqList(BtyGufenzhuanrangParam param, String account) {
        if (ToolUtil.isNotEmpty(account)) {
            Page pageContext = getPageContext();

            //获取用户id
            Long userId = userMapper.getUserId(account);
            param.setCreateUser(userId);
            IPage page = this.baseMapper.fqList(pageContext, param);
            return LayuiPageFactory.createPageInfo(page);
        }

        return new LayuiPageInfo();
    }

    /**
     * 根据姓名查询职位等信息
     *
     * @param name
     * @return
     */
    @Override
    public List<Map> nameList(String name, String account) {

        List<Map> mapList = new ArrayList<>();
        if (ToolUtil.isNotEmpty(name)) {
            mapList = this.baseMapper.nameList(name, null);
        }
        if (ToolUtil.isNotEmpty(account)){
            mapList = this.baseMapper.nameList(null, account);
        }
        return mapList;
    }

    @Override
    public long queryAllDaibanQty(String account) {
        BtyGufenzhuanrangParam param=new BtyGufenzhuanrangParam();
        param.setShStatus(1L);
        LayuiPageInfo data = (LayuiPageInfo)this.gufenList(param,account);
        if(data==null || data.getData()==null){
            return 0;
        }else {
            return data.getData().size();
        }
    }

    /**
     * 股份催办
     * @param btyGufenzhuanrangId
     * @param account
     * @return
     */
    @Override
    public ResponseData gufenUrge(Long btyGufenzhuanrangId, String account) {

        if (ToolUtil.isNotEmpty(account)){
            boolean add = false;
            //获取用户id
            Long userId = userMapper.getUserId(account);

            //根据 btyGufenzhuanrangId 查询当前审批进度
            BtyGufenzhuanrangShepiResult shepi = btyGufenzhuanrangShepiMapper.getShenpi(btyGufenzhuanrangId);

            if (ToolUtil.isNotEmpty(shepi)){
                //待审批状态可催办
                if (!shepi.getShStatus().equals("1")){
                    return ResponseData.success("已审核完不可催办！");

                }else {//待审核
                    String sId = shepi.getBtyGufenzhuanrangShepiId().toString();
                    int jiedian = shepi.getJiedian();
                    String zrTel = shepi.getZrTel();
                    String zrName = shepi.getZrName();
                    String srTel = shepi.getSrTel();
                    User srUser = btyWxMapper.getOpenId(srTel);//受让人id

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = new Date();//催办时间
                    String dateSdf = sdf.format(date);
                    Date endTime = DateUtil.addHour(dateSdf, 4);

                    String[] openid = null;
                    String[] receiveId = null;

                    //查询该店督导
                    String ddTel = teamMapper.getDd(shepi.getShopId());
                    User ddUser = btyWxMapper.getOpenId(ddTel);
                    //查询该店营运经理
                    String yyTel = teamMapper.getYy(shepi.getShopId());
                    User yyUser = btyWxMapper.getOpenId(yyTel);

                    //总部股份审核
                    Long role = 1399903894637486082L;//总部股份审核
                    List<String> openidlist = userService.listOpenidsByRole(role);
                    List<String> useridlist = userMapper.listUseridsByRole(role);

                    //财务股份审核
                    Long cwRole = 1399903976661295105L;//财务股份审核
                    List<String> cwlist = userService.listOpenidsByRole(cwRole);
                    List<String> cwidlist = userMapper.listUseridsByRole(cwRole);

                    /* 1、受让方审核；2、督导审核；3、城市经理审核；4、总部审核；5、财务审核、*/
                    if (jiedian == 1){//推送受让方审核

                        //推送受让方
                        if (ToolUtil.isNotEmpty(srUser)) {
                            openid = new String[]{srUser.getOpenid()};
                            receiveId = new String[]{srUser.getUserId().toString()};
                        }

                    }else if (jiedian == 2){//推送督导审核
                        //推送督导
                        if (ToolUtil.isNotEmpty(ddUser)) {
                            openid = new String[]{ddUser.getOpenid()};
                            receiveId = new String[]{ddUser.getUserId().toString()};
                        }

                    }else if (jiedian == 3){//推送城市经理审核
                        //推送营运经理
                        if (ToolUtil.isNotEmpty(yyUser)) {
                            openid = new String[]{yyUser.getOpenid()};
                            receiveId = new String[]{yyUser.getUserId().toString()};
                        }

                    }else if (jiedian == 4){//推送总部审核
                        //推送总部
                        if (ToolUtil.isNotEmpty(openidlist)) {
                            logger.info("=========总部股份审核:" + openidlist + "========");
                            openid = openidlist.toArray(new String[openidlist.size()]);
                            receiveId = useridlist.toArray(new String[useridlist.size()]);
                        }

                    }else if (jiedian == 5){//推送财务审核
                        //推送财务
                        if (ToolUtil.isNotEmpty(cwlist)) {
                            logger.info("=========财务股份审核:" + cwlist + "========");
                            openid = cwlist.toArray(new String[cwlist.size()]);
                            receiveId = cwidlist.toArray(new String[cwidlist.size()]);
                        }

                    }


                    String receiveUser = StringUtils.join(receiveId, ",");

                    //查询催办表中当天是否催办过
                    List<BtyCuibanResult> btyCuiban = btyCuibanMapper.getCuiban(btyGufenzhuanrangId, sId);
                    //没有催办过
                    if (ToolUtil.isEmpty(btyCuiban)){
//                    if (ToolUtil.isEmpty(btyCuiban) || btyCuiban.size() <= 1){

                        BtyCuibanParam param = new BtyCuibanParam();
                        param.setPId(btyGufenzhuanrangId);
                        param.setSId(sId);
                        param.setType(1);//单据类型；1->股份转让
                        param.setCreateTime(date);
                        param.setEndTime(endTime);
                        param.setCreateUser(userId);
                        param.setReceiveUser(receiveUser);
                        param.setInterval("240分钟");
                        //催办表新增数据
                        add = btyCuibanService.add(param);

                        //催办过
                    }else {
                            //催办过一次
                        if (btyCuiban.size() == 1){
                            //催办截止时间
                            Date endTime1 = btyCuiban.get(0).getEndTime();
                            Date createTime = btyCuiban.get(0).getCreateTime();

                            //毫秒ms
                            long diff = endTime1.getTime() - date.getTime();//已催办间隔
                            long diffDays = diff / (60 * 1000);//计算两个日期相差的分钟数

                            //当前日期>=催办到期时间
                            if (date.after(endTime1)){

                                BtyCuibanParam param = new BtyCuibanParam();
                                param.setPId(btyGufenzhuanrangId);
                                param.setSId(sId);
                                param.setType(1);//单据类型；1->股份转让
                                param.setCreateTime(date);
                                param.setEndTime(endTime);
                                param.setCreateUser(userId);
                                param.setReceiveUser(receiveUser);
                                param.setInterval("240分钟");
                                //催办表新增数据
                                add = btyCuibanService.add(param);

                            }else {
                                return ResponseData.success("请于" + diffDays + "分钟后催办！");
                            }

                        }else {
                            return ResponseData.success("24小时内只能催办两次，今天已到达催办上限！");
                        }
                    }

                    if (add){
                        String now = DateUtil.getNow();//当前时间
                        //获取当前店名
                        String dm = btyBrandMapper.getDm(shepi.getShopId());
                        String data = zrName + "发起了关于" + dm + "的股份转让，需要您审批，请登录web端或小妖app及时处理！";
                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "股份转让审批", "股份转让审批", now, data);

                        weChatSendTempMsgService.sendmsg(openid, BusConst.MSURL, tempObj);
                        logger.info("======已推送催办消息======");
                    }

                }
            }
        }

        return ResponseData.success();
    }

    @Override
    public ResponseData countDown(Long btyGufenzhuanrangId, String account) {
        BtyGufenzhuanrangShepiResult shepi = btyGufenzhuanrangShepiMapper.getShenpi(btyGufenzhuanrangId);

        if (ToolUtil.isNotEmpty(shepi)){
            String sId = shepi.getBtyGufenzhuanrangShepiId().toString();
            //查询该项数据的催办时间
            BtyCuibanResult maxCuiban = btyCuibanMapper.getMaxCuiban(btyGufenzhuanrangId, sId);
            Date date = new Date();
            if (ToolUtil.isNotEmpty(maxCuiban)){
                Date endTime = maxCuiban.getEndTime();
                String time = DateUtil.getTime(endTime, date);
                if (time.contains("-")){
                    return ResponseData.success();
                }
                return ResponseData.success(time);
            }
            return ResponseData.success();
        }

        return ResponseData.success();
    }

    /**
     * 股份转让审核链
     * @return
     */
    @Override
    public ResponseData shChain(Long btyGufenzhuanrangId) {
        List<Map> list = baseMapper.getshChain(btyGufenzhuanrangId);

        GufenzhuanrangResult gufenzhuanrangResult = new GufenzhuanrangResult();

        if (ToolUtil.isNotEmpty(list)){
            for (Map map : list) {

                Long btyGufenzhuanrangId1 = Long.valueOf(map.get("bty_gufenzhuanrang_id").toString());
                gufenzhuanrangResult.setBtyGufenzhuanrangId(btyGufenzhuanrangId1);
                String zrName = map.get("zr_name").toString();//转让方
                gufenzhuanrangResult.setZrName(zrName);
                String zrTime = map.get("create_time").toString();//转让方发起时间
                gufenzhuanrangResult.setZrTime(zrTime);
//                hashMap.put("srName", map.get("sr_name"));//受让方
                //受让方
                if (map.get("jiedian").equals(1)){
                    String srName = map.get("name").toString();
                    gufenzhuanrangResult.setSrName(srName);
                    String srTime= map.get("update_time").toString();
                    gufenzhuanrangResult.setSrTime(srTime);
                }
                //督导
                if (map.get("jiedian").equals(2)){
                    String ddName= map.get("name").toString();
                    gufenzhuanrangResult.setDdName(ddName);
                    String ddTime= map.get("update_time").toString();
                    gufenzhuanrangResult.setDdTime(ddTime);
                }
                //营运经理
                if (map.get("jiedian").equals(3)){
                    String yyName= map.get("name").toString();
                    gufenzhuanrangResult.setYyName(yyName);
                    String yyTime= map.get("update_time").toString();
                    gufenzhuanrangResult.setYyTime(yyTime);
                }
                //总部审核
                if (map.get("jiedian").equals(4)){
                    String zbName= map.get("name").toString();
                    gufenzhuanrangResult.setZbName(zbName);
                    String zbTime= map.get("update_time").toString();
                    gufenzhuanrangResult.setZbTime(zbTime);
                }
                //财务审核
                if (map.get("jiedian").equals(5)){
                    String cwName= map.get("name").toString();
                    gufenzhuanrangResult.setCwName(cwName);
                    String cwTime= map.get("update_time").toString();
                    gufenzhuanrangResult.setCwTime(cwTime);
                }
            }
        }

        return ResponseData.success(gufenzhuanrangResult);
    }

    /**
     * APP-撤回
     * @param btyGufenzhuanrangId
     * @return
     */
    @Override
    public ResponseData recall(Long btyGufenzhuanrangId) {
        //查询是否已审批
        List<Map> list = btyGufenzhuanrangShepiMapper.getList(btyGufenzhuanrangId);
        if (ToolUtil.isNotEmpty(list)){
            //未审批时才可撤回
            if (list.size() == 1 && list.get(0).get("jiedian").equals(1) && list.get(0).get("sh_status").equals("1")){
                //删除子表数据
                btyGufenzhuanrangShepiMapper.deleteByGf(btyGufenzhuanrangId);
                //删除股份转让表数据
                this.removeById(btyGufenzhuanrangId);
            }else {
                //查询已通过的最大节点及审核人
                Map map = btyGufenzhuanrangShepiMapper.getJiedian(btyGufenzhuanrangId);
                String name = "";
                if (map.get("jiedian").equals(1)){
                    name = "受让方";
                }else if (map.get("jiedian").equals(2)){
                    name = "督导";
                }else if (map.get("jiedian").equals(3)){
                    name = "营运经理";
                }else if (map.get("jiedian").equals(4)){
                    name = "总部";
                }else if (map.get("jiedian").equals(5)){
                    name = "财务";
                }
                name = name + map.get("name").toString();
                return ResponseData.error(201, name + "已审批，不可撤回!");
            }
        }
        return ResponseData.success();
    }

    /**
     * APP-校验银行卡信息
     * @param yhk
     * @return
     */
    @Override
    public ResponseData yhkCheak(String yhk) {
        //通过银行卡号获取银行简称
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=" + yhk + "&cardBinCheck=true";
        String content = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(content);
        if (ToolUtil.isNotEmpty(jsonObject.get("bank"))){
            return ResponseData.success();
        }else {
            return ResponseData.error(201,"异常账号!");
        }
    }

    /**
     * APP-判断当前登录者是否是受让方
     * @param tel
     * @return
     */
    @Override
    public ResponseData srCheak(String tel) {
        int i = baseMapper.srCheak(tel);
        return ResponseData.success(i);
    }

    /**
     * 导出列表
     * @param param
     * @return
     */
    @Override
    public List expList(BtyGufenzhuanrangParam param) {
        String account = LoginContextHolder.getContext().getUser().getAccount();
        //查询督导所有的店
        List<String> list = null;
        List<String> ddList = null;
        param.setUserTel(account);
        param.setCreateUser(LoginContextHolder.getContext().getUser().getId());
        /* 1、受让方审核；2、督导审核；3、城市经理审核；4、总部审核；5、财务审核、*/
        //获取当前用户角色列表
        List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();

        if (roleNames.contains("总部股份审核")) {
            param.setJiedian("4");

        }else if (roleNames.contains("营运经理")) {
            //查询营运经理所有的店
            list = teamMapper.getYyCode(account);
            //查询为督导所有的店
            ddList = teamMapper.getDdCode(account);

            if (ddList.size() > 0){
                param.setIsdd("1");
            }

            if (list.size() > 0){
                param.setJiedian("3");
            }else {
                param.setJiedian("1");
            }

        }else if (roleNames.contains("督导")) {
            list = teamMapper.getDdCode(account);

            if (list.size() > 0) {
                param.setJiedian("2");
            }else {
                param.setJiedian("1");
            }

        }else if (roleNames.contains("财务股份审核")) {
            param.setJiedian("5");

        } else {
            param.setJiedian("1");
        }
        List<BtyGufenzhuanrangResult> list1 = this.baseMapper.expList(param, list, ddList);
        return list1;
    }


}
